package com.fqyd.campustransaction.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.fqyd.campustransaction.model.*;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fqyd.campustransaction.utils.Tools;

/**
 * 订单
 */
@Controller
@Scope(value = "prototype")
public class OrderController extends BaseController {

	@RequestMapping("admin_order_list")
	public String goodsList(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("loguser");
		user = userService.getById(user.getId());
		List<Order> orderList = orderService.getByUserId(user.getId());
		List<Order> order = orderService.getAll();
		request.setAttribute("orderList", orderList);
		request.setAttribute("order", order);
		return "admin/order_list";
	}

	@RequestMapping("order_add")
	public String orderAdd(HttpServletRequest request) {
		String type = request.getParameter("type");
		if (Tools.isEmpty(type)) {
			return "redirect:index.do";
		}
		User user = (User) request.getSession().getAttribute("loguser");
		user = userService.getById(user.getId());
		if ("1".equals(type)) {
			List<Cart> carts = cartService.getByUserId(user.getId());
			if (carts.isEmpty()) {
				return "redirect:cart.do";
			}
			String orderId = Tools.createID();
			double totalPrice = 0.0;
			for (int i = 0; i < carts.size(); i++) {
				Goods goods = goodsService.getById(carts.get(i).getGoodsId());
				if (goods == null) {
					continue;
				}
				totalPrice += goods.getPrice().doubleValue();
				goods.setStatus("已出售");
				goodsService.update(goods);
				OrderDetails details = new OrderDetails();
				details.setId(Tools.createID());
				details.setOrderId(orderId);
				details.setOtherId(goods.getId());
				details.setName(goods.getName());
				details.setPicture(goods.getPicture());
				details.setPrice(goods.getPrice());
				orderDetailsService.add(details);
				cartService.delete(carts.get(i).getId());
			}
			Order order = new Order();
			order.setId(orderId);
			order.setUserId(user.getId());
			order.setType(type);
			order.setPrice(BigDecimal.valueOf(totalPrice));
			order.setStatus("待收货");
			order.setCreateTime(new Date());
			orderService.add(order);
		}
		if ("2".equals(type)) {
			String otherId = request.getParameter("other_id");
			if (Tools.isEmpty(otherId)) {
				return "redirect:index_task.do";
			}
			Task task = taskService.getById(otherId);
			if (Tools.isEmpty(otherId)) {
				return "redirect:index_task.do";
			}
			task.setStatus("已接取");
			taskService.update(task);
			String orderId = Tools.createID();
			OrderDetails details = new OrderDetails();
			details.setId(Tools.createID());
			details.setOrderId(orderId);
			details.setOtherId(task.getId());
			details.setName(task.getName());
			details.setPicture(task.getPicture());
			details.setPrice(task.getPrice());
			orderDetailsService.add(details);
			Order order = new Order();
			order.setId(orderId);
			order.setUserId(user.getId());
			order.setType(type);
			order.setPrice(task.getPrice());
			order.setStatus("待完成");
			order.setCreateTime(new Date());
			orderService.add(order);
		}
		return "redirect:personal_order.do";
	}

	@RequestMapping("order_confirm")
	public String orderConfirm(HttpServletRequest request, RedirectAttributes attributes) {
		String type = request.getParameter("type");
		String orderId = request.getParameter("order_id");
		if (Tools.isEmpty(type)) {
			return "redirect:index.do";
		}
		Order order = orderService.getById(orderId);
		if (Tools.isEmpty(orderId)) {
			return "redirect:index.do";
		}
		if ("1".equals(type)) {
			List<OrderDetails> orderDetails = orderDetailsService.getByOrderId(order.getId());
			for (int i = 0; i < orderDetails.size(); i++) {
				Goods goods = goodsService.getById(orderDetails.get(i).getOtherId());
				if (goods == null) {
					continue;
				}
				goods.setStatus("已下架");
				goodsService.update(goods);
			}
		}
		if ("2".equals(type)) {
			List<OrderDetails> orderDetails = orderDetailsService.getByOrderId(order.getId());
			for (int i = 0; i < orderDetails.size(); i++) {
				Task task = taskService.getById(orderDetails.get(i).getOtherId());
				if (task == null) {
					continue;
				}
				task.setStatus("已完成");
				taskService.update(task);
			}
		}
		order.setStatus("已完成");
		orderService.update(order);
		attributes.addFlashAttribute("message", "操作成功：订单（" + order.getId() + "）已完成");
		return "redirect:personal_order.do";
	}

	//Du:搜索订单
	@RequestMapping("order_search")
	public String goods(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("loguser");//从Session中获取用户对象
		String userId = user.getId();//提取用户ID
		String orderId = request.getParameter("orderId");//从前台请求中获取订单ID
		orderId = "%" + orderId + "%";//为数据库模糊查询更改格式
		Order order = new Order();
		order.setId(orderId);
		order.setUserId(userId);
		List<Order> orderList = orderService.getByUserAndOrderId(order);//查询对应用户的订单并返回
		request.setAttribute("orderList", orderList);
		return "admin/order_list";
	}

	//Du:删除订单
	@RequestMapping("order_delete")
	public String orderDelete(HttpServletRequest request, RedirectAttributes attributes) {
		String orderId = request.getParameter("order_id");//从前台接收订单ID
		Order order = orderService.getById(orderId);//从数据库中根据订单ID查询订单
		if (Tools.isEmpty(orderId)) {////如果数据库中无此订单则返回主页
			return "redirect:index.do";
		}
		if(!order.getStatus().equals("待完成") && !order.getStatus().equals("待收货")){//订单为待完成或待收货状态则不可删除
			order.setStatus("已删除");//删除订单
			orderService.update(order);
			attributes.addFlashAttribute("message", "操作成功：订单（" + order.getId() + "）已删除");
		}
		return "redirect:admin_order_list.do";
	}
}
